/**
 * All rights Reserved, Designed By Android_Robot
 *
 * @Title: ZoneHuoDongFragmentNew.java
 * @Package com.jiyi.activity.zone
 * @Description: TODO(用一句话描述该文件做什么)
 * @author: HYM
 * @date: 2017-7-25 上午8:59:54
 * @version V1.0
 */
package com.jiyi.activity.zone;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.OvershootInterpolator;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jiyi.adapter.HuoDongAdapter;
import com.jiyi.bean.zone.HuoDongDetailJson;
import com.jiyi.bean.zone.ZoneHuoDongBean;
import com.jiyi.bean.zone.ZoneHuoDongListJson;
import com.jiyi.bean.zone.ZoneHuoDongParent;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.event.HuoDongListEvent;
import com.jiyi.inteface.HuoDongPopInterface;
import com.jiyi.inteface.WebApi;
import com.jiyi.view.HuoDongPopView;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.DeviceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @ClassName: ZoneHuoDongFragmentNew
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-7-25 上午8:59:54
 *
 */
public class ZoneHuoDongFragmentNew extends Fragment implements
        OnRefreshListener, HuoDongPopInterface {

    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.srlTip)
    SwipeRefreshLayout srlTip;

    @BindView(R.id.tvNull1)
    TextView tvNull1;
    @BindView(R.id.tvNull2)
    TextView tvNull2;

    @BindView(R.id.ivFaBu)
    ImageView ivFaBu;

    @BindView(R.id.mainList)
    ExpandableListView mainList;

    HuoDongAdapter mHuoDongAdapter;

    ArrayList<ZoneHuoDongParent> mHuoDongDatas = new ArrayList<ZoneHuoDongParent>();

    HuoDongPopView mHuoDongPopView;

    // 发布请求事件
    private final int FABU = 1;

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater
                .inflate(R.layout.fragment_huodong_new, null, false);
        ButterKnife.bind(this, view);

        init();
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ivFaBu.setTranslationY(2 * getResources().getDimensionPixelOffset(R.dimen.zone_new));
        ivFaBu.animate()
                .translationY(0)
                .setInterpolator(new OvershootInterpolator(1.f))
                .setStartDelay(500)
                .setDuration(1000)
                .start();


    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Subscribe(sticky = true)
    public void onHuoDongListEvent(HuoDongListEvent huoDongListEvent) {
        int type = huoDongListEvent.type;
        switch (type) {
            case HuoDongListEvent.MY_HUODONG_FRAGMENT:
                getHuoDongData();
                break;

            default:
                break;
        }
    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    private void init() {
        setAdapter();
        getHuoDongData();

        mHuoDongPopView = new HuoDongPopView(this.getContext(), this);
    }

    /**
     * @author: HYM
     * @Title: setAdapter
     * @Description: TODO(这里用一句话描述这个方法的作用) void
     * @date: 2017-7-25
     */
    private void setAdapter() {
        // 设置refreshLayout的监听
        refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
                Color.GREEN);
        refreshLayout.setOnRefreshListener(this);
        srlTip.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
                Color.GREEN);
        srlTip.setOnRefreshListener(this);

        mHuoDongAdapter = new HuoDongAdapter(getContext(), mHuoDongDatas);
        mainList.setAdapter(mHuoDongAdapter);
        mainList.setGroupIndicator(null);// 这个是去掉父级的箭头
        // 点击不能收缩
        mainList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

            @Override
            public boolean onGroupClick(ExpandableListView parent, View v,
                                        int groupPosition, long id) {
                return true;
            }
        });
        mainList.setOnChildClickListener(new OnChildClickListener() {

            @Override
            public boolean onChildClick(ExpandableListView parent, View v,
                                        int groupPosition, int childPosition, long id) {
                ZoneHuoDongBean zoneHuoDongBean = mHuoDongDatas
                        .get(groupPosition).getChildList().get(childPosition);
                getHuoDongDetail(zoneHuoDongBean.getId());
                return true;
            }
        });
    }

    private void getHuoDongData() {
        Map<String, String> params = new HashMap<String, String>();
        params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());

        VolleyRequest.StringRequestPost(getContext(),
                WebApi.ZONE_HUODONG_LIST, "", params, new StringInterface(
                        getContext()) {

                    @Override
                    public void stringSuccess(String result) {
                        if (getActivity() == null
                                || getActivity().isFinishing()) {
                            return;
                        }
                        try {
                            JSONObject obj = new JSONObject(result);
                            String status = obj.getString("status");
                            String info = obj.getString("info");
                            if (status.equals("200")) {
                                ZoneHuoDongListJson temp = new Gson().fromJson(
                                        result, ZoneHuoDongListJson.class);
                                if (temp != null
                                        && temp.getData() != null
                                        && temp.getData().getActList1().size() == 0
                                        && temp.getData().getActList2().size() == 0
                                        && temp.getData().getActList3().size() == 0
                                        && temp.getData().getActList4().size() == 0) {
                                    srlTip.setVisibility(View.VISIBLE);
                                    refreshLayout.setVisibility(View.GONE);
                                    Spannable sTextSpannable = new SpannableString(
                                            tvNull1.getText());
                                    // 改变字体颜色
                                    sTextSpannable
                                            .setSpan(
                                                    new ForegroundColorSpan(
                                                            getResources()
                                                                    .getColor(
                                                                            R.color.tab_top_on)),
                                                    5, 10, 0);
                                    tvNull1.setText(sTextSpannable);
                                    Spannable jiahao = new SpannableString(
                                            tvNull2.getText());
                                    // 改变字体颜色
                                    jiahao.setSpan(
                                            new ForegroundColorSpan(
                                                    getResources().getColor(
                                                            R.color.tab_top_on)),
                                            5, 6, 0);
                                    tvNull2.setText(jiahao);
                                } else {
                                    srlTip.setVisibility(View.GONE);
                                    refreshLayout.setVisibility(View.VISIBLE);
                                    mHuoDongDatas.clear();
                                    ZoneHuoDongParent jxz = new ZoneHuoDongParent();
                                    jxz.setTitle("待开始");
                                    jxz.setChildList(temp.getData()
                                            .getActList1());
                                    mHuoDongDatas.add(jxz);
                                    ZoneHuoDongParent dks = new ZoneHuoDongParent();
                                    dks.setTitle("进行中");
                                    dks.setChildList(temp.getData()
                                            .getActList2());
                                    mHuoDongDatas.add(dks);
                                    ZoneHuoDongParent yjs = new ZoneHuoDongParent();
                                    yjs.setTitle("已结束");
                                    yjs.setChildList(temp.getData()
                                            .getActList3());
                                    mHuoDongDatas.add(yjs);
                                    ZoneHuoDongParent yqx = new ZoneHuoDongParent();
                                    yqx.setTitle("已取消");
                                    yqx.setChildList(temp.getData()
                                            .getActList4());
                                    mHuoDongDatas.add(yqx);
                                    mHuoDongAdapter.notifyDataSetChanged();
                                    for (int i = 0; i < mHuoDongDatas.size(); i++) {
                                        mainList.expandGroup(i);
                                    }
                                }

                            } else {
                                ToastUtil.getInstances().showMsg(info);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } finally {
                            refreshLayout.setRefreshing(false);
                        }
                    }

                    @Override
                    public void stringError(VolleyError error) {
                        refreshLayout.setRefreshing(false);
                        ToastUtil.getInstances().showMsg(R.string.err_http_response);
                    }
                });
    }

    @Override
    public void onRefresh() {
        getHuoDongData();
    }

    /**
     * <p>
     * Title: OnSureListener
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @see HuoDongPopInterface#OnSureListener()
     */
    @Override
    public void OnSureListener() {
        // TODO Auto-generated method stub

    }

    /**
     * <p>
     * Title: OnCancleListener
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @see HuoDongPopInterface#OnCancleListener()
     */
    @Override
    public void OnCancleListener() {
        // TODO Auto-generated method stub

    }

    /**
     * <p>
     * Title: OnShowListener
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @see HuoDongPopInterface#OnShowListener()
     */
    @Override
    public void OnShowListener() {
        // TODO Auto-generated method stub

    }

    /**
     * <p>
     * Title: OnHideListener
     * </p>
     * <p>
     * Description:
     * </p>
     *
     * @see HuoDongPopInterface#OnHideListener()
     */
    @Override
    public void OnHideListener() {
        // TODO Auto-generated method stub

    }

    void getHuoDongDetail(String huoDongId) {
        Map<String, String> params = new HashMap<String, String>();
        params.put(AppConfig.ACCESS_TOKEN, UserInfoUtil.getCurrentUserAccessToken());
        params.put("id", huoDongId);

        VolleyRequest.StringRequestPost(getContext(),
                WebApi.ZONE_HUODONG_DETAIL, "", params, new StringInterface(
                        getContext()) {

                    @Override
                    public void stringSuccess(String result) {
                        try {
                            JSONObject obj = new JSONObject(result);
                            String status = obj.getString("status");
                            String info = obj.getString("info");
                            if (status.equals("200")) {
                                HuoDongDetailJson temp = new Gson().fromJson(
                                        result, HuoDongDetailJson.class);
                                mHuoDongPopView.showPopWindow(temp.getData());
                            } else {
                                ToastUtil.getInstances().showMsg(info);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } finally {
                        }
                    }

                    @Override
                    public void stringError(VolleyError error) {
                        ToastUtil.getInstances().showMsg(R.string.err_http_response);
                    }
                });
    }

    @OnClick({R.id.rlNew, R.id.ivFaBu})
    public void onClick(View view) {
        Intent intent = null;
        switch (view.getId()) {
            case R.id.rlNew:
                intent = new Intent(getActivity(), ZoneAllHuoDongActivity.class);
                startActivity(intent);
                break;
            case R.id.ivFaBu:
                intent = new Intent(getActivity(), HuoDongFaBuActivity.class);
                int[] location = DeviceUtil.getInstance().getLocationOnScreen(ivFaBu);
                int centerX = location[0];//获取当前位置的横坐标
                int centerY = location[1];//获取当前位置的纵坐标
                intent.putExtra("x", centerX);
                intent.putExtra("y", centerY);


                startActivityForResult(intent, FABU);
                break;
            default:
                break;
        }
    }
}
